import { LogicalPosition } from '@tauri-apps/api/window';
import { Menu } from '@tauri-apps/api/menu';
import { emit } from '@tauri-apps/api/event';

const getSelectedText = () => {
  const selection = window.getSelection();
  if (selection && selection.rangeCount > 0) {
    const selectedText = selection.toString();
    return selectedText;
  }
  return null;
}

export type ContextMenuType = 'content' | 'email' | 'folder' | 'default';

const refreshMenu = {
  id: 'refresh',
  text: '刷新',
  action: () => {
    if (_contextmenu) {
      _contextmenu.close();
    }
    location.reload();
  }
};

let _contextmenu: null | Menu = null;

const handlerClick = (operate: string, data: any) => {
  if (_contextmenu) {
    _contextmenu.close();
  }
  emit(operate, data);
}

const showContextMenu = (event: any, type: ContextMenuType = 'default', data?: any) => {
  event.stopPropagation();
  event.preventDefault();
  const items: any[] = [];
  if (type === 'content') {
    const text = getSelectedText();
    if (text) {
      items.push({
        id: 'translate',
        text: '翻译',
        action: () => handlerClick('translate', {
          position: { left: event.clientX, top: event.clientY },
          data: text
        })
      });
      items.push({
        id: 'reply_selected',
        text: '回复',
        action: () => handlerClick('reply_selected', {
          selectedText: text,
          emailData: data
        })
      });
    }
  } else if (type === 'email') {
    const list: any[] = [
      { id: 'unRead', text: '标记为未读' },
      { id: 'moveTo', text: '移动到' },
      { id: 'reply', text: '回复' },
      { id: 'replyAll', text: '回复全部' },
      { id: 'forward', text: '转发' },
    ];
    items.push(...list.map(item => {
      return {
        ...item,
        action: () => handlerClick('emial_operate', {
          operate: item.id,
          data: data
        })
      };
    }));
  } else if (type === 'folder') {
    const list: any[] = [
      { id: 'allRead', text: '全部标为已读' },
      { id: 'addFolder', text: '新建文件夹' },
    ];
    items.push(...list.map(item => {
      return {
        ...item,
        action: () => handlerClick('emial_operate', {
          operate: item.id,
          data: data
        })
      };
    }));
  }

  items.push(refreshMenu);

  Menu.new({
    items: items
  }).then(menu => {
    _contextmenu = menu;
    _contextmenu.popup(new LogicalPosition(event.clientX, event.clientY));
  });
}

export default showContextMenu;